package com.app.micaihu.view.login.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import com.app.base.BaseMvpActivity
import com.app.http.bean.BaseBean
import com.app.micaihu.R
import com.app.micaihu.bean.infor.UserInfor
import com.app.micaihu.configure.Config
import com.app.micaihu.configure.ConfigKeyConstant
import com.app.micaihu.configure.TypeConstant
import com.app.micaihu.manager.AppConfigManager
import com.app.micaihu.manager.UserInforManager
import com.app.micaihu.utils.MobclickAgentUtils
import com.app.micaihu.view.login.contract.LogInContract
import com.app.micaihu.view.login.dialog.ChangeMilitaryDialog
import com.app.micaihu.view.login.presenter.LogInPresenter
import com.app.micaihu.view.login.sy.ConfigUtils
import com.app.micaihu.view.login.utils.CloseLoginActivityUtils
import com.app.micaihu.view.user.userinfo.activity.WebActivity
import com.app.utils.biz.Biz.Companion.instance
import com.baidu.mobstat.StatService
import com.blankj.utilcode.util.*
import com.jeremyliao.liveeventbus.LiveEventBus
import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.bean.SHARE_MEDIA
import kotlinx.android.synthetic.main.login_other_login.*
import kotlinx.android.synthetic.main.login_phone_login_activity.*

/**
 * 手机验证码登录
 */
class PhoneLoginActivity : BaseMvpActivity<LogInContract.View, LogInPresenter>(), LogInContract.View {

    override fun getLayoutId() = R.layout.login_phone_login_activity
    override fun getPresenter() = LogInPresenter()

    var forceLogin = false

    private val umAuthListener: UMAuthListener = object : UMAuthListener {
        override fun onStart(share_media: SHARE_MEDIA) {
            LogUtils.e(classTag, "platform onStart()$share_media")
        }

        override fun onComplete(share_media: SHARE_MEDIA, i: Int, map: Map<String, String>) {
            LogUtils.e(classTag, "platform onComplete()$share_media  ${map.toString()}")
            var nickName: String? = ""
            var headPic: String? = ""
            var fromType = ""
            var openId: String? = ""
            when (platform) {
                SHARE_MEDIA.QQ -> {
                    nickName = map["screen_name"]
                    headPic = map["profile_image_url"]
                    openId = map["openid"]
                    fromType = TypeConstant.QQ_LOGIN
                }
                SHARE_MEDIA.WEIXIN -> {
                    openId = map["openid"]
                    nickName = map["screen_name"]
                    headPic = map["profile_image_url"]
                    fromType = TypeConstant.WEIXIN_LOGIN
                }
                SHARE_MEDIA.SINA -> {
                    openId = map["id"]
                    nickName = map["screen_name"]
                    headPic = map["cover_image_phone"]
                    fromType = TypeConstant.SINA_LOGIN
                }
            }
            mPresenter?.quickLogin(openId, nickName, headPic, fromType)
        }

        override fun onError(share_media: SHARE_MEDIA, i: Int, throwable: Throwable) {
            LogUtils.e(classTag, "platform onError()$share_media  $i   $throwable")
        }

        override fun onCancel(share_media: SHARE_MEDIA, i: Int) {
            LogUtils.e(classTag, "platform onCancel()$share_media  $i  ")
        }
    }
    private var platform: SHARE_MEDIA? = null

    @SuppressLint("SetTextI18n")
    override fun setData() {
        BarUtils.addMarginTopEqualStatusBarHeight(ivBack)
        forceLogin = SPUtils.getInstance().getBoolean(ConfigKeyConstant.forceLogin)
        val military = instance.military
        if (StringUtils.isEmpty(military)) {
            tvTitle.text = "欢迎来到迷彩虎"
        } else {
            tvTitle.text = "欢迎来到迷彩虎${Config.militaryList[military.toInt() - 1]}"
        }

        if (forceLogin) {
            val changeMilitaryDialog = ChangeMilitaryDialog(ActivityUtils.getTopActivity())
            changeMilitaryDialog.setChangeMilitaryListener(object : ChangeMilitaryDialog.OnChangeMilitaryListener {
                @SuppressLint("SetTextI18n")
                override fun changeMilitary(index: Int) {
                    ConfigUtils.tvTitle?.text = "欢迎来到迷彩虎" + Config.militaryList[index - 1]
                    tvTitle?.text = "欢迎来到迷彩虎" + Config.militaryList[index - 1]
                }
            })
            changeMilitaryDialog.show()
        }
    }

    override fun addListeners() {
        ivBack.setOnClickListener {
            if (forceLogin) {
                if (ActivityUtils.isActivityExistsInStack(QuickLoginActivity::class.java)) {
                    finish()
                } else {
                    ActivityUtils.finishAllActivities()
                }
            } else {
                finish()
            }
        }
        tvLoginAccount.setOnClickListener {
            enterPager(AccountLoginActivity::class.java)
        }
        tvChange.setOnClickListener {
            val changeMilitaryDialog = ChangeMilitaryDialog(ActivityUtils.getTopActivity())
            changeMilitaryDialog.setChangeMilitaryListener(object : ChangeMilitaryDialog.OnChangeMilitaryListener {
                @SuppressLint("SetTextI18n")
                override fun changeMilitary(index: Int) {
                    ConfigUtils.tvTitle?.text = "欢迎来到迷彩虎" + Config.militaryList[index - 1]
                    tvTitle?.text = "欢迎来到迷彩虎" + Config.militaryList[index - 1]
                }
            })
            changeMilitaryDialog.show()
        }
        tvLoginCode.setOnClickListener {
            mPresenter?.sendCode(etPhone.text.toString(), TypeConstant.LOGIN_CODE)
        }
        etPhone.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                tvLoginCode.isEnabled = etPhone.text.toString().isNotEmpty()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

        })
        ivQQLogin.setOnClickListener {
            platform = SHARE_MEDIA.QQ
            val installQQ = UMShareAPI.get(thisActivity).isInstall(thisActivity, SHARE_MEDIA.QQ) //判断是否本地有客户端
            if (installQQ) {
                UMShareAPI.get(thisActivity).getPlatformInfo(thisActivity, platform, umAuthListener)
            } else {
                ToastUtils.showShort("请先安装QQ客户端")
            }
        }

        ivWxLogin.setOnClickListener {
            val api = UMShareAPI.get(thisActivity)
            StatService.onEvent(thisActivity, Config.EventBauduId.login_weixin, "成功", 1) // 统计的点击的次数
            MobclickAgentUtils.event(Config.EventBauduId.login_weixin, "成功")
            platform = SHARE_MEDIA.WEIXIN
            val install = api.isInstall(thisActivity, SHARE_MEDIA.WEIXIN) //判断是否本地有客户端
            if (install) {
                api.getPlatformInfo(thisActivity, platform, umAuthListener)
            } else {
                MobclickAgentUtils.event(Config.EventBauduId.login_weixin, "请先安装微信客户端")
                StatService.onEvent(thisActivity, Config.EventBauduId.login_weixin, "请先安装微信客户端", 1) // 统计的点击的次数
                ToastUtils.showShort("请先安装微信客户端")
            }
        }

        ivSinaLogin.setOnClickListener {
            val api = UMShareAPI.get(thisActivity)
            StatService.onEvent(thisActivity, Config.EventBauduId.login_sina, "成功", 1) // 统计的点击的次数
            MobclickAgentUtils.event(Config.EventBauduId.login_sina, "成功")
            platform = SHARE_MEDIA.SINA
            val install = api.isInstall(thisActivity, SHARE_MEDIA.SINA) //判断是否本地有客户端
            if (install) {
                api.getPlatformInfo(thisActivity, platform, umAuthListener)
            } else {
                ToastUtils.showShort("请先安装微博客户端")
            }

        }
        tvUserProtocol.setOnClickListener {
            //用户协议
            val userAgreementUrl = AppConfigManager.getInstance().configSP.getString(ConfigKeyConstant.userAgreementUrl, "")
            val bundle = Bundle()
            bundle.putString(Config.Extra.url, userAgreementUrl)
            enterPager(WebActivity::class.java, bundle)
        }
        tvPrivacyProtocol.setOnClickListener {
            //隐私协议
            val privateAgreementUrl = AppConfigManager.getInstance().configSP.getString(ConfigKeyConstant.privateAgreementUrl, "")
            val bundle = Bundle()
            bundle.putString(Config.Extra.url, privateAgreementUrl)
            enterPager(WebActivity::class.java, bundle)
        }
    }

    override fun handleSendCode(result: BaseBean<Any?>?) {
        hideLoading()
        if (result == null) {
            ToastUtils.showShort(getString(R.string.net_error))
        } else {
            if (result.isSuccess()) {
                val bundle = Bundle()
                bundle.putString(Config.Extra.phone, etPhone.text.toString())
                enterPager(PhoneCodeActivity::class.java, bundle)
            } else {
                ToastUtils.showShort(result.msg)
            }
        }


    }

    override fun handleLogin(login: BaseBean<UserInfor?>?) {
        if (login == null) {
            ToastUtils.showShort(getString(R.string.net_error))
        } else {
            if (login.isSuccess()) {
                login.data?.let {
                    //设置用户信息
                    UserInforManager.getInstance().userInfor = it;//设置用户信息
                    //保存到本地
                    UserInforManager.getInstance().saveUserInfor(it)
                    //拉取任务数据
                    if (forceLogin) {
                        UserInforManager.getInstance().getUserTask(this, false)
                    } else {
                        UserInforManager.getInstance().getUserTask(this, true)
                    }
                    LiveEventBus.get(Config.EventBus.loginSuccess).post(true)
                    if (it.mobile.isEmpty()) {
                        val bundle = Bundle()
                        bundle.putBoolean(Config.Extra.showSkip, true)
                        enterPager(BindPhoneActivity::class.java, bundle)
                    }
                    CloseLoginActivityUtils.closeAllLoginActivity()
                }
            } else {
                ToastUtils.showShort(login.msg)
            }
        }

    }

    override fun onBackPressed() {
        if (forceLogin) {
            if (ActivityUtils.isActivityExistsInStack(QuickLoginActivity::class.java)) {
                super.onBackPressed()
            } else {
                ActivityUtils.finishAllActivities()
            }
        } else {
            super.onBackPressed()
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
    }
}